package com.example.blog.controller;

import com.example.blog.pojo.Message;
import com.example.blog.pojo.User;
import com.example.blog.service.MessageService;
import com.example.blog.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.security.auth.Subject;
import java.util.List;
import java.util.Random;

/**
 * name: 东北宋小宝
 * date: 2020/9/5
 */
@Controller
public class MessageShowController {
    @Resource
    private MessageService messageService;
    @Value("${blogpage.userName}")
    private String myname;

    @GetMapping("/message")
    public String toMessage(){
        return "message";
    }

    @PostMapping("/message")
    public String toMessage(Message  message, RedirectAttributes redirectAttributes){
        User user = (User)SecurityUtils.getSubject().getPrincipal();
        if (user != null) {
            message.setAdminMessage(true);
            message.setNickname(user.getNickname());
        }
        if (myname.trim().equals(message.getNickname())) {
            Random random = new Random();
            Integer i = random.nextInt(999)+random.nextInt(999);
            message.setNickname("User"+i.toString());
        }
        messageService.saveMessage(message);
        return "redirect:/message";
    }

    @GetMapping("/comment")
    public String comment(Model model){

        List<Message> messages = messageService.getAllMessage();
        model.addAttribute("messages",messages);
        model.addAttribute("blogname",myname);
        return "message ::messages";
    }
}
